import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import request from '@/utils/request'

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem('token') || '')
  const user = ref(JSON.parse(localStorage.getItem('user') || 'null'))

  const isAuthenticated = computed(() => !!token.value)
  const isAdmin = computed(() => user.value?.role === '0' || user.value?.role === 0)

  // 登录
  const login = async (username, password) => {
    try {
      const response = await request.post('/auth/login', {
        username,
        password
      })
      
      console.log('登录响应:', response)
      
      if (response.code === 200) {
        token.value = response.data.token
        user.value = response.data.user
        
        localStorage.setItem('token', token.value)
        localStorage.setItem('user', JSON.stringify(user.value))
        
        console.log('登录成功，token:', token.value)
        console.log('用户信息:', user.value)
        console.log('token已保存到localStorage:', localStorage.getItem('token'))
        
        return { success: true }
      }
      console.log('登录失败:', response.message)
      return { success: false, message: response.message }
    } catch (error) {
      console.error('登录异常:', error)
      return { success: false, message: error.response?.data?.message || '登录失败' }
    }
  }

  // 注册
  const register = async (userInfo) => {
    try {
      const response = await request.post('/auth/register', userInfo)
      return {
        success: response.code === 200,
        message: response.message || (response.code === 200 ? '注册成功' : '注册失败')
      }
    } catch (error) {
      return { success: false, message: error.response?.data?.message || '注册失败' }
    }
  }

  // 登出
  const logout = () => {
    token.value = ''
    user.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  }

  // 初始化token
  const initAuth = () => {
    // 由于使用统一的request实例，token会在请求拦截器中自动添加
    console.log('初始化认证，token:', token.value)
  }

  return {
    token,
    user,
    isAuthenticated,
    isAdmin,
    login,
    register,
    logout,
    initAuth
  }
}) 